package com.ybt.communicate.ws.client;

import javax.xml.namespace.QName;

import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;
import org.apache.log4j.Logger;

import com.ybt.communicate.core.IConnection;
import com.ybt.communicate.core.IProtocol;
import com.ybt.communicate.core.exception.ProtocolException;
import com.ybt.communicate.ws.configration.WSRuntimeConfig;

public class WSClientRPC implements IProtocol {
    private static Logger logger = Logger.getLogger(WSClientRPC.class);
    private boolean start;
    private WSRuntimeConfig config;

    public WSClientRPC(WSRuntimeConfig config) {
        super();
        this.config = config;
    }

    public IConnection createConnection() throws ProtocolException {
        // TODO Auto-generated method stub
        try {
            RPCServiceClient serviceClient = new RPCServiceClient();
            //设置ws地址
            Options options = serviceClient.getOptions();
            EndpointReference targetEPR = new EndpointReference(config
                    .getTarget());
            options.setTo(targetEPR);

            //创建连接
            WSClientRPCConnection c = new WSClientRPCConnection(serviceClient,
                    config);
            
            //设置rpc方法
            QName opAddEntry = new QName(config.getTargetNamespace(), config
                    .getMethod());
            c.setOperator(opAddEntry);
            
            return c;
        } catch (AxisFault e) {
            // TODO Auto-generated catch block
            throw new ProtocolException(e);
        }
    }

    public boolean isStart() {
        // TODO Auto-generated method stub
        return start;
    }

    public void start() throws ProtocolException {
        // TODO Auto-generated method stub
        if (start) {
            // 客户端已经启动
            logger.debug("the client connecting to " + config.getTarget()
                    + " is already started");
            return;
        }

        start = true;
        logger.debug("the client connecting to " + config.getTarget()
                + " has started ...");
    }

    public void stop() throws ProtocolException {
        // TODO Auto-generated method stub
        if (!start) {
            // 客户端已经启动
            logger.debug("the client connecting to " + config.getTarget()
                    + " is already stopped");
            return;
        }
        start = false;
        logger.debug("the client connecting to " + config.getTarget()
                + " has stopped ...");
    }

}
